<?php
/*
 * 支付宝2.0支付
 * @author qiaohongbo
 */
namespace app\components\pay;

use app\models\StudentPaymentDetail;
use app\models\StudentCoefficientState;
use app\models\StudentCoefficientValue;
use app\models\StudentServiceCharge;
use Yii;
use app\components\Func;
use app\components\KelaileJava;

use app\models\Order;
use app\models\OrderPay;
use app\models\App;
use app\models\AppBind;
use app\models\StudentOrder;
use app\models\StudentVipMembers;


class KouBeiPay extends Pay {

    const PREPAY_URL = 'superpay/nativepay'; //主扫
    const QRPAY_URL = 'superpay/micropay'; //被扫
    const REFUND = 'superpay/refund'; //退款
    const QUERY_ORDER = 'superpay/queryOrderNo'; //查询真实18位订单号
    const QUERY_URL = 'superpay/query'; //查询

    static private $pay_qr = ''; //二维码
    public $accountId; //支付号
    //public $storeId; //口碑门店编码
    //public $isv_pid;
    //public $merchant_id; //中信支付宝'商户识别号',中信进件生成

    public function __construct($accountId = '') {
        $this->accountId = $accountId;
    }

    //预支付,返回二维码(主扫)
    public function prepay(array $params) {
        if(!isset($params['device_no'])) throw new \Exception('device_no为空',2022019);
        if(!isset($params['out_trade_no'])) throw new \Exception('out_trade_no为空',2022015);
        if(!isset($params['total_fee'])) throw new \Exception('total_fee为空',2022016);
        if(!isset($params['body'])) throw new \Exception('body为空',2022017);
        $params['notify_url'] = Func::getHostInfo() . '/' . KelaileJava::NOTIFY_URL;
        $params['account_info'] = [
            KelaileJava::KOUBEI_PAY => [
                'account_id' => $this->accountId,
                'store_id' => isset($params['store_id']) ? $params['store_id'] : '',
                'isv_pid' => isset($params['isv_pid']) ? $params['isv_pid'] : '',
            ],
        ];
        $javaRes = self::getResBuyJavaApi(self::PREPAY_URL, $params);
        return $javaRes;
    }

    //刷卡支付(被扫)
    public function micropay(array $params) {
        if(!isset($params['device_no'])) throw new \Exception('device_no为空',2022019);
        if(!isset($params['out_trade_no'])) throw new \Exception('out_trade_no为空',2022015);
        if(!isset($params['total_fee'])) throw new \Exception('total_fee为空',2022016);
        if(!isset($params['auth_code'])) throw new \Exception('auth_code为空',2022020);
        if(!isset($params['body'])) throw new \Exception('body为空',2022017);
        $params['notify_url'] = Func::getHostInfo() . '/' . KelaileJava::NOTIFY_URL;
        if(isset($params['merchant_id'])) $account_info_key = KelaileJava::CITIC_ALI;
        else $account_info_key = KelaileJava::KOUBEI_PAY;
        $params['account_info'] = [
            $account_info_key => [
                'account_id' => $this->accountId,
                'store_id' => isset($params['store_id']) ? $params['store_id'] : '',
                'isv_pid' => isset($params['isv_pid']) ? $params['isv_pid'] : '',
                'merchant_id' => isset($params['merchant_id']) ? $params['merchant_id'] : '',
                'seller_id' => isset($params['seller_id']) ? $params['seller_id'] : '',
            ],
        ];
        $javaRes = self::getResBuyJavaApi(self::QRPAY_URL, $params);
        return $javaRes;
    }

    //退款
    public function refund(array $params) {
        if(!isset($params['out_trade_no'])) throw new \Exception('out_trade_no为空',2022015);
        if(!isset($params['refund_amount'])) throw new \Exception('refund_amount为空',2022021);
        if(!isset($params['refund_reason'])) throw new \Exception('refund_reason为空',2022022);  //退款原因:设备号,标识客来乐设备退款
        $javaRes = self::getResBuyJavaApi(self::REFUND, $params);
        if($javaRes['res']['status'] != '1') throw new \Exception($javaRes['res']['sub_msg']);
        return [
            'refund_trade_no' => $javaRes['res']['refund_trade_no'], //java生成
            'refund_trade_id' => $javaRes['res']['transaction_id'], //退款交易流水号
        ];
    }

    public function getPayQr($order) {
        if(!empty(self::$pay_qr)) return self::$pay_qr;
        try {
            $params = [
                'device_no' => $order->device_no,
                'out_trade_no' => $order->our_trade_no,
                'total_fee' => $order->getPayFee(),
                'body' => $order->shop->name,
                'store_id' => isset($params['store_id']) ? $params['store_id'] : '',
                'isv_pid' => isset($params['isv_pid']) ? $params['isv_pid'] : '',
            ];
            $javaRes = $this->prepay($params);
            if(!empty($javaRes['res']['info'][KelaileJava::KOUBEI_PAY])) {
                self::$pay_qr = $javaRes['res']['info'][KelaileJava::KOUBEI_PAY];
            } else {
                Func::yiilog('KouBiePay => getPayQr: null');
                Func::yiilog($javaRes);
            }    
        } catch (\Exception $e) {
            Func::yiilog('KouBiePay => getPayQr:'.$order->device_no.':'.$e->getMessage());
        }
        return self::$pay_qr;
    }
    
    /**
     * 支付成功
     * @param array $postArr java返回的数据
     */
    public static function paySuccess($postArr, $order) {
        $resArr = $postArr;
        $pay_type = OrderPay::PAY_TYPE_KOUBEI;
        if($resArr['pay_type'] == KelaileJava::CITIC_ALI) $pay_type = OrderPay::PAY_TYPE_CITIC_ALI;
        $order->pay_type = $pay_type;
        $order->status = ($resArr['pay_status'] == '1') ? Order::STATUS_PAY_END : Order::STATUS_PAY_FAIL;
        //$order->out_trade_no = $resArr['transaction_id']; //交易流水号
        $order->ptime = $resArr['pay_time'];
        $order->third_discount_fee += $resArr['ent_discount_fee']; //商家优惠
        $order->third_pay_discount_fee += $resArr['discount_fee']; //支付平台补贴
        $order->saveRedis();
        
        if($resArr['pay_status'] != '1') throw new \Exception($resArr['pay_msg']);
        
        $orderPay = new OrderPay();
        $orderPay->order_id = $order->id;
        $orderPay->enterprise_id = $order->enterprise_id;
        $orderPay->shop_id = $order->shop_id;
        $orderPay->befrom = $order->befrom;
        $orderPay->device_no = $order->device_no;
        $orderPay->cashier_id = $order->cashier_id;
        $orderPay->pay_type = $pay_type;
        $orderPay->pay_fee = $resArr['receipt_amount']; //商家实收金额
        $orderPay->payee = $resArr['account'];  //收款人
        $orderPay->payer = $resArr['payer'];    //付款人
        $orderPay->trade_id = $resArr['transaction_id'];//交易流水号
        $orderPay->utime = $resArr['pay_time'];
        $orderPay->discount_fee = $order->discount_fee;
        $orderPay->third_discount_fee = $order->third_discount_fee;
        $orderPay->saveRedis();

        //支付宝校园卡
        $aliSchoolApp = AppBind::getObj(App::APP_SCHOOL_CARD, AppBind::TYPE_SHOP, $order->shop_id)->getUseObj()->getConfigObj();
        if($aliSchoolApp->getAppState()){
            $userObj = StudentVipMembers::getInstance($resArr['payer'], $order->enterprise_id);
            if(!empty($userObj)) StudentOrder::saveOrder($order->id,$userObj->student_id);

            //校园消费系数 管理费 统计
            $stateObj = StudentCoefficientState::getInstance($order->shop_id);
            if(!empty($stateObj) && $stateObj->state != StudentCoefficientState::STATE_OFF) {
                $service_fee = StudentCoefficientValue::getServiceCharge($order->id, $orderPay->pay_fee);
                $serviceChargeObj = new StudentServiceCharge();
                $serviceChargeObj->order_id = $order->id;
                $serviceChargeObj->service_fee = $service_fee;
                $serviceChargeObj->save(false);
            }
        }


        //小额缴费
        $onlinePaymentApp = AppBind::getObj(App::APP_SCHOOL_ONLINE_PAYMENT, AppBind::TYPE_ENTERPRISE, $order->enterprise_id)->getUseObj()->getConfigObj();
        //支付宝2.0 与小额缴费应用同时开启 需判断订单来源
        if($onlinePaymentApp->getAppState() && $orderPay->befrom == Order::BEFROM_SCHOOL_ONLINE_PAYMENT ) {
            $paymentOrder = Yii::$app->redis_php->get('ali_online_payment:'.$orderPay->order_id);
            StudentPaymentDetail::savePaymentOrder($paymentOrder, $orderPay->order_id, $resArr['pay_time'], $orderPay->pay_fee, OrderPay::PAY_TYPE_KOUBEI);
        }

    }

    public function cancel(array $paras) {
        
    }

    public function checkNotifySign($paras) {
        
    }

    public function getSign($paras) {
        
    }

    public function orderquery(array $paras) {
        if(!isset($paras['out_trade_no']))throw new \Exception('out_trade_no为空',2022015);
        if(!isset($paras['is_push']))$paras['is_push'] = 'false';
        return self::getResBuyJavaApi(self::QUERY_URL, $paras);
    }

    public function refundquery(array $paras) {
        
    }

    //获取支付成功通知url
    public function notifyurl($citic = 0) {
        return Func::getHostInfo() . '/' . KelaileJava::NOTIFY_URL;
    }

}